﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

using EasyProp.Extensions;
using Castle.Core.Interceptor;

namespace EasyProp
{
    public class NotifyPropertyChanged : IPropertySetterFilter
    {
        #region IPropertySetterFilter Members

        public bool Execute(IInvocation invocation, string propertyName)
        {
            // Get the field storing the delegate list created by the PropertyChanged event.
            FieldInfo fieldInfo = invocation.TargetType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
                .Where(f => f.FieldType == typeof(PropertyChangedEventHandler))
                .FirstOrDefault();

            if (fieldInfo != null)
            {
                PropertyChangedEventHandler eventHandler = fieldInfo.GetValue(invocation.InvocationTarget) as PropertyChangedEventHandler;
                if (eventHandler != null)
                {
                    eventHandler.Invoke(invocation.InvocationTarget, new PropertyChangedEventArgs(propertyName));
                }
            }

            return true;
        }

        #endregion

    }
}
